package function;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import entity.BookType;
import interfaces.BookTypeDao;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class BookTypeBaseDao2Impl extends BaseDao2<BookType> implements BookTypeDao {

    /**
     * 单例模式
     */
    private  static BookTypeBaseDao2Impl bookTypeBaseDao=null;

    private BookTypeBaseDao2Impl() {
    }

    public static BookTypeBaseDao2Impl getBookTypeBaseDao(){
        if(bookTypeBaseDao==null) {
            bookTypeBaseDao = new BookTypeBaseDao2Impl();
        }
    return bookTypeBaseDao;
    }

    @Override
    public boolean insert(Connection conn, String name) {
        String sql="insert into `book_type` (`type_name`) value(?)";
        int update = 0;
        try {
            update = update(conn, sql, name);
        } catch (MySQLIntegrityConstraintViolationException throwables) {
            System.out.print("读者类型名重复。");
        }
        if(update==0){
            return false;
        }
        return true;
    }

    @Override
    public boolean deleteById(Connection conn, int id)  {
        String sql="delete from book_type where id=?";
        int update = 0;
        try {
            update = update(conn, sql, id);
        } catch (MySQLIntegrityConstraintViolationException throwables) {
            System.out.println("该书本类型还在被使用，如若要删除请先修改相关书本的书本类型");
        }
        if(update==0){
            return false;
        }
        return true;
    }

    @Override
    public boolean update(Connection conn, int id, String name) {
       String sql="update book_type set type_name=? where id=?";
        int update = 0;
        try {
            update = update(conn, sql, name, id);
        } catch (MySQLIntegrityConstraintViolationException throwables) {
            System.out.println("读者类型名已存在");
        }
        if(update==0){
            return false;
        }
        return true;
    }

    @Override
    public BookType getBookTypeById(Connection conn, int id) {
        String sql="select id id,type_name typeName from book_type where id=?";
        BookType bookType = getInstance(conn, sql, id);
        return bookType;
    }

    @Override
    public BookType getBookTypeByName(Connection conn, String name) {
        String sql="select id id,type_name typeName from book_type where type_name=?";
        BookType instance = getInstance(conn, sql, name);
        return instance;
    }

    @Override
    public List<BookType> getAll(Connection coon) {
        String sql="select id id,type_Name typeName from book_type";
        List<BookType> all = getForList(coon,sql);
        if(all.size()==0){
            return null;
        }
        return all;
    }


}
